<template>
  <div class="taskList">
    <div class="search" @click="fn_jump2Search">
      <div class="search_bg">
        <van-icon name="search" size="0.18rem" />查找
      </div>
    </div>

    <!-- start 刷新按钮 -->
    <div class="updata_btn updata_btn_active" @click="fn_updata">
      <van-icon name="replay" size="0.2rem" />
    </div>
    <!-- end 刷新按钮 -->

    <!-- start tab切换 -->
    <div class="content">
      <van-tabs v-model="activeTab" @change="fn_tabChange" type="card">
        <van-tab name="first" title="执行中">
          <gzhb-item
            :user="user"
            :dataList="totleData.doTasks"
            @jump2Detail="(...arg)=> fn_jump2Detail(...arg, 1)"
          ></gzhb-item>
        </van-tab>
        <van-tab name="second" title="待审批">
          <gzhb-item
            :dataList="totleData.approveTasks"
            @jump2Detail="(...arg)=> fn_jump2Detail(...arg, 2)"
          ></gzhb-item>
        </van-tab>
        <van-tab name="third" title="已完成">
          <gzhb-item
            :dataList="totleData.finishTasks"
            @jump2Detail="(...arg)=> fn_jump2Detail(...arg, 3)"
          ></gzhb-item>
        </van-tab>
      </van-tabs>
    </div>
    <!-- end tab切换 -->

    <!-- start loading -->
    <gzhb-loading :isShow="isLoading"></gzhb-loading>
    <!-- end loading -->
  </div>
</template>

<script>
import axios from '@/axios'
import { mapGetters } from 'vuex'
import { utils_getLocal } from "@/utils/index.js"
export default {
  name: 'TaskList',
  data () {
    return {
      testUser: {
        testOAuthUser: ''
      },
      isLoading: true,
      typeList: [],
      searchForm: {
        principal: "1",
        datetype: '',
        stat: ["LL", "YY", "EE"]
      },
      totleData: {
        doTasks: [],
        approveTasks: [],
        finishTasks: []
      },
      user: {},

      activeTab: 'first',
      isFirstListCome: true
    }
  },
  computed: {
    ...mapGetters(['isFirstCome'])
  },
  created () {
    // 设置用户权限(有token字段就储存，否则不进行操作)
    let token = this.$route.query.token
    if (token) localStorage.setItem('token', token)

    // 默认跳转的tab标签（不存在则跳转第一个标签）
    this.activeTab = this.$route.query.activetab || this.activeTab

    // 如果是开发环境，则添加测试工号
    if (process.env.NODE_ENV === 'production') {
      this.testUser = {}
    } else {
      let userId = localStorage.getItem('userID')
      userId === 'undefined' ? this.testUser.testOAuthUser = '121720' : this.testUser.testOAuthUser = userId
    }

    this.getLabelAndType()
    this.getTotalData()
  },
  activated () {
    // 跳转到对应的tab页签
    this.fn_jump2Tab()

    // 页面首次加载也会被激活
    // 状态不一样，跳转得tab页会不一样
    if (this.$route.params.isSearchUpdata) {
      this.searchForm = this.$route.params.searchForm
      this.getTotalData()
    } else if (!this.isFirstListCome) {
      let id = utils_getLocal('id')
      if (id) {
        this.fn_updataTaskById()
      }
    }

    this.isFirstListCome = false
  },
  methods: {
    async getTotalData () {
      this.isLoading = true
      let thirdDateObj = {}

      //当用户第一次点击搜索的时候，（审批接口 tab===second）年份才跟搜索的年份走，否则都是全年
      if (this.isFirstCome) {
        thirdDateObj = { datetype: '1' }
      }

      if (this.activeTab === 'first') {

        // 第一个tab（first）
        this.getTaskListData(2, this.searchForm).then((res) => {
          this.totleData.approveTasks = res.tasks
        })
        this.getTaskListData(3, this.searchForm, thirdDateObj).then((res) => {
          this.totleData.finishTasks = res.tasks
        })
        let resFirst = await this.getTaskListData(1, this.searchForm)
        this.totleData.doTasks = resFirst.tasks
        this.isLoading = false
      } else if (this.activeTab === 'second') {

        // 第二个tab（second）
        this.getTaskListData(1, this.searchForm).then((res) => {
          this.totleData.doTasks = res.tasks
        })
        this.getTaskListData(3, this.searchForm, thirdDateObj).then((res) => {
          this.totleData.finishTasks = res.tasks
        })
        let resSecond = await this.getTaskListData(2, this.searchForm)
        this.totleData.approveTasks = resSecond.tasks
        this.isLoading = false
      } else {

        // 第三个tab（third）
        this.getTaskListData(1, this.searchForm).then((res) => {
          this.totleData.doTasks = res.tasks
        })
        this.getTaskListData(2, this.searchForm).then((res) => {
          this.totleData.approveTasks = res.tasks
        })
        let resThird = await this.getTaskListData(3, this.searchForm, thirdDateObj)
        this.totleData.finishTasks = resThird.tasks
        this.isLoading = false
      }
    },
    // 获取 数据 （旧的接口）
    getTaskListData (type, obj, other = {}) {
      return axios.post('getTaskList', {
        weekStart: 2,
        datetypeWay: 1,
        dataType: type,
        ...this.testUser,
        ...obj,
        ...other
      })
    },
    // 获取 搜索页面标签跟类型 进行中的数据
    getLabelAndType () {
      axios.post('getTaskListPara').then(res => {
        if (res.success) this.fn_setUserAndSearchInfo(res)
      })
    },
    // 获取单挑任务的数据
    getTaskData () {
      return axios.get('findTaskById', {
        params: {
          id: utils_getLocal('id')
        }
      })
    },
    // 设置用户信息，和搜索需要的任务类型，任务标签
    fn_setUserAndSearchInfo (res) {
      this.user = res.user
      localStorage.setItem('labels', JSON.stringify(res.labels))
      localStorage.setItem('typeList', JSON.stringify(res.typeList))
    },
    // 切换tab选项
    fn_tabChange (event) {
      this.activeTab = event
    },
    // 跳转搜索
    fn_jump2Search () {
      localStorage.setItem('activeTab', this.activeTab)
      this.$router.push({ name: 'taskSearch' })
    },
    // 跳转到详情
    fn_jump2Detail (item, page) {
      this.$router.push({
        path: '/task/detail',
        query: {
          ...this.testUser,
          id: item.uid,
          page
        }
      })
    },
    //状态不一样，跳转得tab页会不一样
    fn_jump2Tab () {
      if (this.$route.params.activeTab === 'second') {
        this.activeTab = 'second'
      }
    },
    // 刷新
    fn_updata () {
      this.getTotalData()
    },
    // 更新单挑任务（删除/更新）
    fn_updataTaskById () {
      let data = []
      switch (this.activeTab) {
        case 'first':
          data = this.totleData.doTasks || []
          break;
        case 'second':
          data = this.totleData.approveTasks || []
          break;
        default:
          data = this.totleData.finishTasks || []
          break;
      }

      // 查找任务对应的index值，如果index在当前的tab中存在，则替换数据
      let index = this.fn_findIndexById(data)

      if (index < 0) return
      let reg = /^3/

      this.getTaskData().then(res => {
        // 当是执行中(first)的时候，判断是否是在途状态，没有则删除，有就替换原来的数据
        if (this.activeTab === 'first') {
          // 返回的状态码是3开头的时候，隐藏该任务    
          let stat = res.masterTask.stat || ''
          if (reg.test(stat)) {
            this.$delete(data, index)
          } else {
            this.$set(data, index, res.masterTask)
          }
        } else if (this.activeTab === 'second') {
          // 当是待审批(second)的时候，判断是否是在途状态（根据ontheWayObj是否有值），没有则删除，有就替换原来的数据
          if (Object.keys(res.ontheWayObj).length) {
            this.$set(data, index, res.masterTask)
          } else {
            this.$delete(data, index)
          }
        }
      })
    },
    // 通过id获取数据的index位置
    fn_findIndexById (data) {
      let id = utils_getLocal('id')
      let result = ''
      data.forEach((item, index) => {
        if (item.uid === id) result = index
      })
      return result
    }
  }
}
</script>

<style lang="less">
.content /deep/ {
  flex: 1;
  overflow: hidden;
  .van-tabs {
    height: 100%;
    display: flex;
    flex-direction: column;
    .van-tabs__wrap {
      height: 0.4rem;
      .van-tabs__nav--card {
        margin: 0;
        border: none;
        height: 0.4rem;
        .van-tab {
          color: #3d3d3d;
          border-right: none;
          line-height: 0.4rem;
          border-bottom: 3px solid #e2e4e6;
          background-color: white;
          .van-tab__text {
            font-size: 0.16rem;
          }
        }
        .van-tab.van-tab--active {
          border-bottom: 3px solid #05a6e4;
          color: #05a6e4;
        }
      }
    }

    .van-tabs__content {
      flex: 1;
      overflow: hidden;
      .van-tab__pane {
        height: 100%;
      }
    }
  }
}
</style>

<style lang="less" scoped>
.taskList {
  display: flex;
  flex-direction: column;
  height: 100%;
  .search {
    padding: 0.05rem 0.07rem;
    height: 0.4rem;
    color: #9a9a9a;
    background-color: #0089f1;
    .search_bg {
      display: flex;
      justify-content: center;
      align-items: center;
      border-radius: 0.1rem;
      height: 0.3rem;
      background-color: white;
      span {
        font-size: 0.16rem;
        line-height: 0.17rem;
      }
    }
  }

  // 刷新按钮
  .updata_btn {
    position: fixed;
    bottom: 0.3rem;
    right: 0.2rem;
    border-radius: 50%;
    width: 0.4rem;
    height: 0.4rem;
    box-shadow: 0 0 10px #bcbaba;
    display: flex;
    justify-content: center;
    align-items: center;
    z-index: 99;
  }
  // .updata_btn_active{

  // }
  // @keyframes animation {

  // }
}
</style>